import logging
import time

from sms import send_sms
from mqtt import mqtt_client


def ms_to_days_and_hours(milliseconds):
    # 一天的毫秒数
    milliseconds_per_day = 24 * 60 * 60 * 1000

    # 计算完整天数
    days = milliseconds // milliseconds_per_day

    # 计算剩余的毫秒数
    remaining_milliseconds = milliseconds % milliseconds_per_day

    # 将剩余的毫秒数转换为小时
    hours = remaining_milliseconds / (60 * 60 * 1000)

    if days == 0:
        return f"{int(hours)}小时"
    else:
        return f"{int(days)}日"


def alarm1_handle(alarm_data: dict):
    logging.debug("alarm1_handle: %s", str(alarm_data))
    voice = f"{alarm_data['deviceType']}警报 {alarm_data['relatedEntity']}的监测仪{alarm_data['deviceName']},触发报警"
    logging.info(voice)
    logging.info("alarm1_handle: %s", str(alarm_data))
    mqtt_client.send_msg(voice)


# def alarm2_handle(alarm_data: dict):
#     # {1}-{2}-{3} {4}:{5}:{6}，{7}的监测仪,前{8}三轴倾角变化速率最大值达到{9}度；前{10}三轴倾角变化最大值达到{11}度触发红色预警。
#     local_time = time.localtime()
#     rate_time = ms_to_days_and_hours(alarm_data["changeRate_ts"])
#     quantity_time = ms_to_days_and_hours(alarm_data["changeQuantity_ts"])
#     abs_max_rate = alarm_data["absMaxRate"]
#     abs_max_quantity = alarm_data["absMaxQuantity"]
#     did = alarm_data["deviceName"]
#     sms_param2 = [local_time.tm_year, local_time.tm_mon, local_time.tm_mday, local_time.tm_hour, local_time.tm_min,
#                   local_time.tm_sec,
#                   alarm_data["relatedEntity"], did, rate_time, abs_max_rate, quantity_time, abs_max_quantity]
#     sms_param = [str(item) for item in sms_param2]
#     logging.info("alarm2_handle: %s", str(alarm_data))
#     if alarm_data["deviceType"] == "倾角传感器":
#         logging.info(
#             "{}-{}-{} {}:{}:{}，{}的监测仪{}(倾角),前{}三轴倾角变化速率最大值达到{}度；前{}三轴倾角变化最大值达到{}度触发红色预警。".format(
#                 sms_param[0], sms_param[1], sms_param[2], sms_param[3], sms_param[4], sms_param[5],
#                 sms_param[6], sms_param[7], sms_param[8], sms_param[9], sms_param[10], sms_param[11]))
#         # send_sms(sms_param, ["QJ", 0])
#     elif alarm_data["deviceType"] == "裂缝传感器":
#         # {1}-{2}-{3} {4}:{5}:{6}，{7}的监测仪{8}(裂缝),前{9}裂缝变形量达到{10}毫米,触发红色预警。
#         # 请监测预警人员时刻加强分析研判、及时上报；请公路巡检人员加强巡视排查、及时记录并上报现场情况；省级公路突发事件综合应急工作领导小组加强值守指导和现场管控，紧急组织转移受威胁人员，并采取危险区封闭、交通管制等措施，严禁非应急人员进入危险区，做好应急各项准备。
#         logging.info(
#             "{}-{}-{} {}:{}:{}，{}的监测仪{}(裂缝),前{}裂缝变形量达到{}毫米,触发红色预警。".format(
#                 sms_param[0], sms_param[1], sms_param[2], sms_param[3], sms_param[4], sms_param[5],
#                 sms_param[6], sms_param[7], sms_param[10], sms_param[11])
#         )
#         sms_param = [sms_param[0], sms_param[1], sms_param[2], sms_param[3], sms_param[4], sms_param[5],
#                      sms_param[6], sms_param[7], sms_param[10], sms_param[11]]
#         # send_sms(sms_param, ["LF", 0])
#
#     logging.debug(alarm_data)
#     print(sms_param)

def get_phone_info(data,alarm_type):
    # [{'name': '张三', 'phone': '1503333333', 'levels': ['红色预警', '橙色预警', '黄色预警']}]
    phone_list = []

    for item in data:
        if alarm_type in item["levels"]:
            phone_list.append(item["phone"])
    return phone_list

def alarm2_handle(alarm_data: dict):
    location:str = alarm_data["relatedEntity"]
    sms_param = {
        "alarmType": alarm_data["alarmType"],
        "location":"s"
    }
    if location.startswith("商登"):
        sms_param["location"] = "s"
    elif location.startswith("郑民"):
        sms_param["location"] = "z"
    else:
        logging.error("未知的location: %s", location)
        return

    phone_list = get_phone_info(alarm_data["ss_phoneDataList"], alarm_data["alarmType"])
    logging.info(phone_list)
    send_sms(sms_param, phone_list)





